<template>
    <div>
        <el-upload
                action="actionUrl"
                list-type="picture-card"
                :on-remove="handleRemove"
                :http-request="handleUploadImage"
                :file-list="fileList"
                ref="upload"
                accept=".jpg,.png,.bmp,.gif,.jpeg"
                :on-preview="handlePictureCardPreview"
        >
            <i slot="default" class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>
<script>
  import {addUploadImageApi} from '@/api/common.js'
  export default {
    name: 'UploadImagesCover',
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        actionUrl: '',
        fileList: [], // 默认显示在页面的数据，不动
        uploadList: [] // 重新定义一个数组来接收图片
      }
    },
    props: {
      uploadImagesList: {
        type: Array,
        default: () => []
      }
    },
    watch: {
      // // 深入监听对象，属性改变时触发函数
      uploadImagesList (newVal) {
        console.log('监听轮播图')
        // 注意：页面显示的图片，格式是{url: ''}
        // 如果后台返回的字段不是url，你需要自己构建出符合的对象出来
        let newImages = JSON.parse(JSON.stringify(newVal))
        this.uploadList = JSON.parse(JSON.stringify(newVal))
        this.fileList = newImages
      }
    },
    methods: {
      // 预览
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 删除
      handleRemove(file) {
        // 根据url唯一标识删除图片（之后需要上传到服务器的url）
        for (let i = 0; i < this.uploadList.length; i++) {
            if (file.url === this.uploadList[i].url) {
              this.uploadList.splice(i, 1)
              this.getData()
              return
            }
        }
      },

      // 图片上传
      handleUploadImage (require) {
        let check = this.handleCheck(require)
        let uploadFilesLast = this.$refs.upload.uploadFiles.length -1
        let fileDom = this.$refs.upload.uploadFiles
        if (!check) {
          fileDom.splice(uploadFilesLast, 1)
          return
        }
        fileDom[uploadFilesLast].status = 'uploading'
        let params = {
          // other: '' , // 额外参数
          file: require.file // 图片字段
        }
        let formData = this.getFormData(params)
        addUploadImageApi(formData)
          .then((data) => {
            let imageObj = {
              path: data.path,
              url: data.url
            }
            this.handleCoverImageUrl(require, data.url)
            this.uploadList.push(imageObj)
            this.getData()
          })
          .catch(() => {
                console.log('上传失败。。。')
                fileDom.splice(uploadFilesLast, 1)
            })
          .finally(() => {
            fileDom[uploadFilesLast].status = ''
          })
      },
      // 覆盖原先的本地url路径
      handleCoverImageUrl (params, url) {
        // 通过uid定位当前上传是哪一张图片
        this.$refs.upload.uploadFiles.map(item => {
          if (item.uid == params.file.uid) {
            item.url = url
          }
        })
      },
      // 上传前校验
      handleCheck (params) {
        const file = params.file,
          fileType = file.type,
          isImage = fileType.indexOf('image') != -1,
          isLt2M = file.size / 1024 / 1024 < 2;
        // 这里常规检验，看项目需求而定
        if (!isImage) {
          this.$message.error("只能上传图片格式png、jpg、gif!");
          return;
        }
        if (!isLt2M) {
          this.$message.error("只能上传图片大小小于2M");
          return;
        }
        return true
      },
      // 设置表单提交数据
      getFormData (params) {
        let formData = new FormData()
        for (let key in params) {
          // params[key] instanceof File （true, 表单传进来了二进制文件）
          if (typeof params[key] !== 'object' || params[key] instanceof File) {
            formData.append(key, params[key])
          } else {
            formData.append(key, JSON.stringify(params[key]))
          }
        }
        return formData
      },
      // 将图片返给父组件
      getData () {
        this.$emit('getData', this.uploadList)
      }
    }
  }
</script>
